<template>
  <div class="traffic-view">
    <map-nav>
      <live-trafic></live-trafic>
      <video-monitor></video-monitor>
      <add-event></add-event>
      <event-query></event-query>
      <EventUpdates></EventUpdates>
      <add-notice></add-notice>
      <traffic-information></traffic-information>
      <map-tools></map-tools>
    </map-nav>
    <map-init></map-init>
  </div>
</template>

<script setup>
import LiveTrafic from '@/components/common/LiveTrafic.vue'
import VideoMonitor from '@/components/traffic/VideoMonitor.vue'
import AddEvent from '@/components/traffic/AddEvent.vue'
import EventQuery from '@/components/traffic/EventQuery.vue'
import EventUpdates from '@/components/traffic/EventUpdates.vue'
import AddNotice from '@/components/traffic/AddNotice.vue'
import TrafficInformation from '@/components/traffic/TrafficInformation.vue'
import MapTools from '@/components/common/MapTools.vue'
import MapInit from '@/components/MapInit.vue'
import MapNav from '@/components/MapNav.vue'

import { ref, onBeforeUnmount, onUnmounted } from 'vue'
import { useMapStore } from '@/stores/mapStore'
import { ElMessage } from 'element-plus'
import { getAllDataByLayerIndex } from '@/api/mapgis-api/getAllDataByLayerIndex'

const mapStore = useMapStore()
const source = ref(null)
const areaLayer = ref(null)
// WebSocket 连接
const socket = new WebSocket('ws://localhost:8080')

// 监听 WebSocket 消息
socket.addEventListener('message', (event) => {
  try {
    const message = JSON.parse(event.data)
    if (message.type === 'userStatusUpdate') {
      const updatedUser = message.user
      // 检查当前用户是否被下线
      const userId = localStorage.getItem('userId')
      // 处理强制下线
      if (userId && String(updatedUser.id) === userId && !updatedUser.isOnline) {
        ElMessage.warning('您已被管理员强制下线，请重新登录')
        // 清除本地存储的用户信息
        localStorage.removeItem('token')
        localStorage.removeItem('userId')
        // 跳转到登录页面，强制整个页面重新加载
        window.location.href = '/login'
      }
    }
  } catch (error) {
    console.error('消息解析失败:', error)
  }
})

/* getAllDataByLayerIndex(0)
  .then((features) => {
    if (mapStore.mapInstance) {
      const colors = ['#2E86C1', '#27AE60', '#F1C40F', '#E74C3C', '#8E44AD']
      source.value = new window.ol.source.Vector()
      source.value.addFeatures(features)

      // 按顺序分配颜色
      source.value.getFeatures().forEach((feature, index) => {
        feature.set('colorGroup', index % colors.length)
      })

      areaLayer.value = new window.ol.layer.Vector({
        name: '居民地',
        source: source.value,
        style: function (feature) {
          const colorIndex = feature.get('colorGroup')
          return new window.ol.style.Style({
            fill: new window.ol.style.Fill({
              color: colors[colorIndex],
            }),
          })
        },
      })
      mapStore.mapInstance.addLayer(areaLayer.value)
    }
    console.log('居民地数据加载成功')
  })
  .catch((error) => {
    console.error('加载错误:', error)
  })

// 组件卸载时清理
onBeforeUnmount(() => {
  const map = mapStore.mapInstance
  // 清理图层
  if (map && areaLayer.value) {
    map.removeLayer(areaLayer.value)
    areaLayer.value.dispose()
  }
  // 清理数据源
  if (source.value) {
    source.value.clear()
    source.value.dispose()
  }
}) */

// 关闭 WebSocket 连接
onUnmounted(() => {
  socket.close()
})
</script>

<style lang="scss" scoped>
.traffic-view {
  position: relative;
  height: 100vh;

  :deep(.map-nav) {
    position: absolute;
    width: 100vw;
    top: 0;
  }

  :deep(.map-container) {
    position: absolute;
    height: 94vh;
    width: 100vw;
    bottom: 0;
  }
}
</style>
